package edu.cmu.cs214.hw9.db.DAO;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import edu.cmu.cs214.hw9.db.SQLiteAdapter;
import edu.cmu.cs214.hw9.db.DAO.User;
import edu.cmu.cs214.hw9.resources.Constants;

/**
 * Handles looking up and inserting into the Users table.
 * @author Peter
 *
 */
public class UserDAO extends SQLiteAdapter {

	public UserDAO() throws Exception 
	{
		super();
	}
	
	/**
	 * Finds a user given a username.
	 * @param email
	 * @return
	 */
	public User findUser(String email)
	{
		User ret = null;
		ResultSet rs = null;
		try 
		{
			String statement = "SELECT * FROM " + Constants.USERS_TABLE + " WHERE email=?;";
			PreparedStatement ps = conn.prepareStatement(statement);
			ps.setString(1, email);
			rs = ps.executeQuery();
			while(rs.next())
				ret = new User(rs.getInt("id"), rs.getString("email"));

		} 
		catch (SQLException e) 
		{
			e.printStackTrace();
		} 
		finally 
		{
            try
            {
            	if(rs != null)
            		rs.close();
            } 
            catch (SQLException e)
            {
            }
        }
		
		return ret;
	}
	
	/**
	 * Finds a user given the user's id.
	 * @param id
	 * @return
	 */
	public User findUser(int id)
	{
		User ret = null;
		ResultSet rs = null;
		try 
		{
			String statement = "SELECT * FROM " + Constants.USERS_TABLE + " WHERE id=?;";
			PreparedStatement ps = conn.prepareStatement(statement);
			ps.setString(1, id + "");
			
			rs = ps.executeQuery();
			while(rs.next())
				ret = new User(rs.getInt("id"), rs.getString("email"));
		} 
		catch (SQLException e) 
		{
			e.printStackTrace();
		} 
		finally 
		{
            try
            {
            	if(rs != null)
            		rs.close();
            } 
            catch (SQLException e)
            {
            }
		}
		return ret;
	}
	
	/**
	 * Creates a user given an email and password
	 * @param email
	 * @param password
	 * @return true if successful, false otherwise.
	 */
	public boolean createUser(String email, String password)
	{
		User lookup = findUser(email);
		if(lookup != null)
			return false;
		
		PreparedStatement ps;
		String statement = "INSERT INTO " + Constants.USERS_TABLE + " (email, password) VALUES (?, ?)";
		try
		{
			ps = conn.prepareStatement(statement);
			ps.setString(1, email);
			ps.setString(2, password);
			ps.executeUpdate();
		} 
		catch(SQLException e)
		{
			e.printStackTrace();
			return false;
		}
		
		return true;
	}
}